package controller

import (
	"fmt"
	"time"

	"github.com/6tail/lunar-go/HolidayUtil"
	"github.com/6tail/lunar-go/calendar"
)

type CalendarDay struct {
	SolarDate     string   `json:"solarDate"`     // 阳历日期
	LunarDate     string   `json:"lunarDate"`     // 阴历日期
	GanZhi        string   `json:"ganZhi"`        // 干支
	Constellation string   `json:"constellation"` // 星座
	Animal        string   `json:"animal"`        // 生肖
	Festivals     []string `json:"festivals"`     // 节日
	SolarTerms    string   `json:"solarTerms"`    // 节气
	WorkdayStatus string   `json:"workdayStatus"` // 工作日状态
	LuckyThings   []string `json:"luckyThings"`   // 宜
	UnluckyThings []string `json:"unluckyThings"` // 忌
}

type Rili struct {
	Base
}

func NewRili() *Rili {
	return &Rili{}
}
func (r *Rili) GetDayDetail(year, month, day int) CalendarDay {

	// 转化时间
	solar := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local)
	// 获取阳历信息
	d := calendar.NewSolarFromDate(solar)

	lunar := calendar.NewLunarFromDate(solar)
	m := lunar.GetMonthInChinese()
	days := lunar.GetDayInChinese()
	// 阳历日期
	LunarDate := fmt.Sprintf("%s月%s", m, days)

	// // 获取节日信息
	l := d.GetFestivals()
	//国内节日
	festivals := make([]string, 0)
	for i := l.Front(); i != nil; i = i.Next() {
		festivals = append(festivals, i.Value.(string))
	}
	// 获取其他节日信息
	l = d.GetOtherFestivals()
	for i := l.Front(); i != nil; i = i.Next() {
		festivals = append(festivals, i.Value.(string))
	}

	// 获取节气信息
	solarTerm := lunar.GetJieQi()

	ganzhi := lunar.GetDayInGanZhiExact()

	// 获取星座信息
	constellation := d.GetXingZuo()

	// 获取生肖信息
	animal := lunar.GetYearShengXiao()
	// 获取宜忌信息
	l = lunar.GetDayYi()
	lunckyThings := make([]string, 0)
	for i := l.Front(); i != nil; i = i.Next() {
		lunckyThings = append(lunckyThings, i.Value.(string))
	}
	// 忌(流派2)
	l = lunar.GetDayJiBySect(2)
	unluckyThings := make([]string, 0)
	for i := l.Front(); i != nil; i = i.Next() {
		unluckyThings = append(unluckyThings, i.Value.(string))
	}

	return CalendarDay{
		SolarDate:     solar.Format("2006-01-02"),
		LunarDate:     LunarDate,
		GanZhi:        ganzhi,
		Constellation: constellation,
		Animal:        animal,
		Festivals:     festivals,
		SolarTerms:    solarTerm,
		WorkdayStatus: getWorkdayStatus(solar),
		LuckyThings:   lunckyThings,
		UnluckyThings: unluckyThings,
	}
}

func getWorkdayStatus(date time.Time) string {
	b := HolidayUtil.GetHoliday(date.Format("2006-01-02"))
	if b != nil {
		if b.IsWork() {
			return "上班"
		} else {
			return b.GetName()
		}
	}
	return ""
}

func (r *Rili) GetMonthData(year, month int) map[string]CalendarDay {
	daysInMonth := time.Date(year, time.Month(month+1), 0, 0, 0, 0, 0, time.Local).Day()

	result := make(map[string]CalendarDay)

	for day := 1; day <= daysInMonth; day++ {
		date := time.Date(year, time.Month(month), day, 0, 0, 0, 0, time.Local)
		dateStr := date.Format("2006-01-02")
		result[dateStr] = r.GetDayDetail(year, month, day)
	}

	return result
}
